/**
 * 触摸摇杆控件
 * Author           : wangjun
 * Date             : 2017-04-11
 */

cc.Class({
    extends: cc.Component,

    properties: {
       
    },

    onLoad: function () {
          this.touchValid = true;
        this.touchAreaRedius = 100;

        this.circle = cc.find('circle', this.node);
        this.stick  = cc.find('stick', this.node);
        this.stick.opacity = 0;

        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchBegin, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    },

    onTouchBegin: function(event) {
        var localPos = this.node.convertTouchToNodeSpace(event);
        localPos = cc.v2(localPos.x - this.node.width / 2, localPos.y - this.node.height / 2);

        if (localPos.mag() > this.touchAreaRedius){
            this.touchValid = false;
        }
        else {
            this.touchValid = true;
            this.stick.opacity = 255;
            this.updateStick(localPos);
        }
        
        event.stopPropagation();
    },

    onTouchMove: function(event) {
        var localPos = this.node.convertTouchToNodeSpace(event);
        localPos = cc.v2(localPos.x - this.node.width / 2, localPos.y - this.node.height / 2);
        if (localPos.mag() <= this.touchAreaRedius && this.touchValid){
            this.updateStick(localPos);
           
        }
        else {
            this.touchValid = false;
            this.stopStick();
        }

        event.stopPropagation();
    },

   onTouchEnd: function(event) {
        this.stopStick();
        this.ontouch();
        this.touchValid = true;

        event.stopPropagation();
    },

    onTouchCancel: function(event) {
        this.stopStick();
        this.ontouch();
        this.touchValid = true;

        event.stopPropagation();
    },

    updateStick: function(pos) {
        if (pos == cc.Vec2.ZERO){
            this.stopStick();
        }
        else {
            var angle = pos.signAngle(cc.v2(1, 0));
            this.stick.setPosition(Math.cos(angle) * 39, Math.sin(angle) * 39);
            
            var event = new cc.Event.EventCustom('joystick_move', true);
            event.setUserData({angle: -angle});
            this.node.dispatchEvent(event);
        }
    },

    stopStick: function(){
        this.stick.opacity = 0;
        this.stick.setPosition(cc.Vec2.ZERO);

        var event = new cc.Event.EventCustom('joystick_stop', true);
        this.node.dispatchEvent(event);
    },

  

    ontouch : function(){

        var event = new cc.Event.EventCustom('touch', true);

        this.node.dispatchEvent(event);
    }
});
